import { getRates } from "../services/rates.js";
import { getFromStorage, saveToStorage } from "../storage.js";

export class CurrencyConverter {
  constructor(root) {
    this.root = root;
    this.render();
  }
  async render() {
    this.root.innerHTML = `
      <div class="row">
        <input id="ccAmount" type="number" step="0.01" value="1" />
        <select id="ccFrom"></select>
        <span>→</span>
        <select id="ccTo"></select>
      </div>
      <div class="display" id="ccResult">0</div>
    `;
    this.amountEl = this.root.querySelector("#ccAmount");
    this.fromEl = this.root.querySelector("#ccFrom");
    this.toEl = this.root.querySelector("#ccTo");
    this.resultEl = this.root.querySelector("#ccResult");

    const rates = await getRates();
    const currencies = Object.keys(rates.rates).concat([rates.base]).sort();
    const last = (await getFromStorage("cc_prefs")) || {
      from: rates.base,
      to: "USD",
    };
    for (const code of currencies) {
      const o1 = document.createElement("option");
      o1.value = code;
      o1.textContent = code;
      this.fromEl.appendChild(o1);
      const o2 = document.createElement("option");
      o2.value = code;
      o2.textContent = code;
      this.toEl.appendChild(o2);
    }
    this.fromEl.value = last.from;
    this.toEl.value = last.to;

    const onChange = () => this.update(rates);
    this.amountEl.addEventListener("input", onChange);
    this.fromEl.addEventListener("change", onChange);
    this.toEl.addEventListener("change", onChange);

    this.update(rates);
  }
  async update(rates) {
    const amount = Number(this.amountEl.value || "0");
    const { base, rates: table } = rates;
    const from = this.fromEl.value;
    const to = this.toEl.value;
    await saveToStorage("cc_prefs", { from, to });

    const toBase = from === base ? amount : amount / (table[from] || 1);
    const result = to === base ? toBase : toBase * (table[to] || 1);
    this.resultEl.textContent = `${result.toFixed(4)} ${to}`;
  }
}
